package com.gxa.autoparts.portal.controller;

import com.gxa.autoparts.core.common.ExceptionCode;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.gxa.autoparts.core.common.JsonResult;
import com.gxa.autoparts.core.exception.BusinessException;
import com.gxa.autoparts.core.pojo.BalanceDetails;
import com.gxa.autoparts.core.pojo.PayInfo;
import com.gxa.autoparts.core.pojo.User;
import com.gxa.autoparts.core.util.SnowFlakeUtil;
import com.gxa.autoparts.portal.service.BalanceDetailsService;
import com.gxa.autoparts.portal.service.MyOrderService;
import com.gxa.autoparts.portal.service.PayInfoService;
import com.gxa.autoparts.portal.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@Transactional(rollbackFor = Throwable.class)
@CrossOrigin
@RequestMapping("/user")
@Api(tags = "用户（我的）")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    BalanceDetailsService balanceDetailsService;

    @Autowired
    HttpServletRequest request;

    @Autowired
    PayInfoService payInfoService;


    @Autowired
    MyOrderService myOrderService;


    private SimpleDateFormat simpleDateFormat =   new SimpleDateFormat("yyyy-MM-dd");

    @PostMapping("/checkMyInfo")
    @ApiOperation("查看个人信息（个人信息页面渲染使用）")
    public Map checkMyInfo(Long id){
        User user = userService.selectById(id);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setData(user);
        return jsonResult.getDataMap();
    }
    @PostMapping("/changeinfo")
    @ApiOperation("更改个人信息（修改出生日期在另外一个借口测试）")
    public Map changeinfo(User user){
        Integer integer = userService.updateById(user);
        JsonResult jsonResult = new JsonResult();
        if (integer > 0){

            jsonResult.setCode("200");
            jsonResult.setMsg("修改成功");
        }
        return jsonResult.getDataMap();
    }

    @PostMapping("/updatePwd")
    @ApiOperation("修改密码的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "需要修改密码的用户id",required = true,paramType = "query",dataType = "Long"),
            @ApiImplicitParam(name = "oldPwd",value = "原密码",required = true,paramType = "query",dataType = "String"),
            @ApiImplicitParam(name = "newPwd",value = "新密码",required = true,paramType = "query",dataType = "String"),
            @ApiImplicitParam(name = "secondPwd",value = "第二次新密码",required = true,paramType = "query",dataType = "String")
    })
    public Map updatePwd(Long id,String oldPwd,String newPwd,String secondPwd) throws BusinessException {
        User user = userService.selectById(id);

        if (oldPwd != null && !oldPwd.equals(user.getPwd())){
            throw new BusinessException(ExceptionCode.OLDPWD_CHECK_FAILED);
        }
        if (newPwd != null && !newPwd.equals(secondPwd)){
            throw new BusinessException(ExceptionCode.DOUBLEPWD_WRONG);
        }
        user.setPwd(newPwd);
        userService.updateById(user);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("修改成功");
        return jsonResult.getDataMap();

    }
    @PostMapping("/changeBirth")
    @ApiOperation("修改出生日期")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "long",paramType = "query"),
            @ApiImplicitParam(name = "birthday",value = "新的出生日期",required = true,dataType = "string",paramType = "query")
    })
    public Map changeBirth(Long id,String birthday) throws ParseException {
        User user = new User();
        Date newBirthday = simpleDateFormat.parse(birthday);
        user.setId(id);
        user.setBirthday(newBirthday);
        Integer integer = userService.updateById(user);
        JsonResult jsonResult = new JsonResult();
        if (integer > 0){

            jsonResult.setCode("200");
            jsonResult.setMsg("修改成功");
        }
        return jsonResult.getDataMap();
    }
    @PostMapping("/checkMyBalance")
    @ApiOperation("查看我的余额")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "long",paramType = "query")
    })
    public Map checkMyBalance(Long id) throws ParseException {

        User user = userService.selectById(id);

        JsonResult jsonResult = new JsonResult();
        jsonResult.put("balance",user.getBalance());
        return jsonResult.getDataMap();

    }
    @GetMapping("/pay")
    @ApiOperation("余额充值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "payMoney",value = "用户实付款",required = true,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name = "getMoney",value = "用户充值总额",required = true,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "long",paramType = "query")
    })
    public String pay(String payMoney,Long id,String getMoney){
        String url = "https://openapi.alipaydev.com/gateway.do";
        AlipayClient alipayClient = new DefaultAlipayClient(url, "2021000118686863", "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC0zSPmUmUFqrM9ZidjzwW4o4yhppDzx8InRThuoVpqAUWUejr2h4HgeIofO+eeMhw3ikuXyaJE7krEsvQeXTkCITkr4g3Q3LY3DMRTkG17eX74ddvuSoVT1cvjR3VB9XjQ4JwpUIlDEa+zmbAyW73Nq8xUba1jPM/rU4Ml7wr4bLLicy0vAA0JuO2mFoe9p0zKSJXv3nfm53WVXTeovxgPsYZufu2RzwqWsG3Mn5HCADpoUMLYBt4HawBXTZPb/tMAdvQdlReFegMgbcfjiOq6KjzbQONB4qjLra9upK6LP6sUipu7j+sSBe/BK9rUZYxBMxC+pzpAO3iIwZwmzRzZAgMBAAECggEATaSK9i4MFBLqRkPIRqRw4Inbqs/ND+OJDTQ8t8Wy/jLtnoWfLJ+ktrENH7yqCtWaKH/LVrPQa6mpki8HhsKh6Lg7xQyewkMGPT3OUdSEL7JNRIXYnMyD1SzLEh9ty5WO/KR4a4WabKL7wTUO5ZFgQSK17Mvs2eETqQuEFpZBL81FJK7pbPC0yXAuAP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oG9jnf3mCxMCl5WQxc44Y/7Bu/mJYmQTMVLBBrUyG5d3YgfwtdZD43gSpzLdQqTBaxwoAKgpC1nXPVbPE5AiGImgYtG8W4bgzrdrckUZ8FRMwRVhUz8XKOmVwehZQDEvDEM2QvECAHeWQ5Uu27yYOi8JFPD4hsinAbdYOaa27CRXK89BY4NWngLvMiopG2gShFaRGaeAS5w2PAs4gusQwsY46BEaWkTQ9Z8mCz4VZeY0tV8a/l5g1iEP0Dntu3DKHUMNFjk/AM0XmwJIXW06GSfW37XlLduWA7AMeRsppBTspOYsZkqCnsA2JnIg+sL2iJEG1FcXjgahQIDAQAB", "RSA2"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://localhost:8081/user/payReturn?getMoney="+getMoney+"&payMoney="+payMoney+"&id="+id);
        alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
        String payOrderId = UUID.randomUUID().toString();
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":"+"'"+payOrderId+"'"+"," +
                " \"total_amount\":"+"'"+payMoney+"'"+"," +
                " \"subject\":\"充值业务\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }
    @GetMapping("/payReturn")
    public void payReturn(){
        BalanceDetails balanceDetails = new BalanceDetails();
        balanceDetails.setCreateTime(new Date());
        balanceDetails.setMoney(Double.parseDouble(request.getParameter("getMoney")));
        balanceDetails.setReason("充值");
        balanceDetails.setUid(Long.parseLong(request.getParameter("id")));
        balanceDetailsService.insert(balanceDetails);
        User user = new User();
        user.setId(Long.parseLong(request.getParameter("id")));
        user.setBalance(user.getBalance()+Double.parseDouble(request.getParameter("getMoney")));
        userService.updateById(user);

    }

    @GetMapping("/aliPay")
    @ApiOperation("使用支付宝购买商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "payMoney",value = "用户实付款",required = true,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name = "getMoney",value = "用户充值总额",required = true,dataType = "string",paramType = "query"),
            @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "long",paramType = "query")
    })
    public String aliPay(Long orderId){
        Double money = myOrderService.getMoney(orderId);
        String url = "https://openapi.alipaydev.com/gateway.do";
        AlipayClient alipayClient = new DefaultAlipayClient(url, "2021000118686863", "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC0zSPmUmUFqrM9ZidjzwW4o4yhppDzx8InRThuoVpqAUWUejr2h4HgeIofO+eeMhw3ikuXyaJE7krEsvQeXTkCITkr4g3Q3LY3DMRTkG17eX74ddvuSoVT1cvjR3VB9XjQ4JwpUIlDEa+zmbAyW73Nq8xUba1jPM/rU4Ml7wr4bLLicy0vAA0JuO2mFoe9p0zKSJXv3nfm53WVXTeovxgPsYZufu2RzwqWsG3Mn5HCADpoUMLYBt4HawBXTZPb/tMAdvQdlReFegMgbcfjiOq6KjzbQONB4qjLra9upK6LP6sUipu7j+sSBe/BK9rUZYxBMxC+pzpAO3iIwZwmzRzZAgMBAAECggEATaSK9i4MFBLqRkPIRqRw4Inbqs/ND+OJDTQ8t8Wy/jLtnoWfLJ+ktrENH7yqCtWaKH/LVrPQa6mpki8HhsKh6Lg7xQyewkMGPT3OUdSEL7JNRIXYnMyD1SzLEh9ty5WO/KR4a4WabKL7wTUO5ZFgQSK17Mvs2eETqQuEFpZBL81FJK7pbPC0yXAuAPsx3MTy8p07fiMM+H46wg+iOimZ+g5u3UcxQSh2jZvzVSje0T+7ZSNyjH3in60KTW//Mg1hwekUGwO5yhRCRSmrCXZH9EV034ZhyM47sWRwc1RrEvSkaL9uMZSBnbuFnXViorZb1aRGR14R0C2a/oysMGfgAQKBgQDksWOuOKZjEtfSnyplBH5H5QF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4NWngLvMiopG2gShFaRGaeAS5w2PAs4gusQwsY46BEaWkTQ9Z8mCz4VZeY0tV8a/l5g1iEP0Dntu3DKHUMNFjk/AM0XmwJIXW06GSfW37XlLduWA7AMeRsppBTspOYsZkqCnsA2JnIg+sL2iJEG1FcXjgahQIDAQAB", "RSA2"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl("http://localhost:8081/user/aliPayReturn?orderId="+orderId);
        alipayRequest.setNotifyUrl("http://domain.com/CallBack/notify_url.jsp");//在公共参数中设置回跳和通知地址
        Long payOrderId = SnowFlakeUtil.nextId();
        alipayRequest.setBizContent("{" +
                " \"out_trade_no\":"+"'"+payOrderId+"'"+"," +
                " \"total_amount\":"+"'"+money+"'"+"," +
                " \"subject\":\"充值业务\"," +
                " \"product_code\":\"QUICK_WAP_PAY\"" +
                " }");//填充业务参数
        String form="";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return form;
    }

    @GetMapping("/aliPayReturn")
    public void aliPayReturn(){
        // 从请求头拿到订单编号
        Long orderId = Long.parseLong(request.getParameter("orderId"));
        // 生成支付流水号
        Long l = SnowFlakeUtil.nextId();
        myOrderService.overOrder(orderId,l);
        Map<String, Object> orderIdBySerialnNumber = myOrderService.findOrderIdBySerialnNumber(orderId);
        // s生成支付信息
        PayInfo payInfo = new PayInfo();
        payInfo.setId(SnowFlakeUtil.nextId());
        payInfo.setOrderId(Long.parseLong(orderIdBySerialnNumber.get("id").toString()));
        payInfo.setPayPrice(Double.parseDouble(orderIdBySerialnNumber.get("realPrice").toString()));
        payInfo.setPayTime(new Date());
        payInfo.setPayType("支付宝");
        payInfoService.insert(payInfo);
    }

    @PostMapping("/payByBalance")
    @ApiOperation("使用余额支付接口")
    @ApiImplicitParam(name = "orderId",value = "订单编号")
    public Map payByBalance(Long orderId) throws BusinessException {

        Long l = SnowFlakeUtil.nextId();
        // 完善订单信息
        myOrderService.overOrder(orderId,l);
        // 通过订单编号找到订单id和价格
        Map<String, Object> orderIdBySerialnNumber = myOrderService.findOrderIdBySerialnNumber(orderId);
        User user = userService.selectById(Long.parseLong(orderIdBySerialnNumber.get("userId").toString()));
        Double price = Double.parseDouble(orderIdBySerialnNumber.get("realPrice").toString());
        if (user.getBalance() < price){
            throw new BusinessException(ExceptionCode.BALANCE_LOW);
        }
        user.setBalance(user.getBalance()-price);
        userService.updateById(user);
        PayInfo payInfo = new PayInfo();
        payInfo.setId(SnowFlakeUtil.nextId());
        payInfo.setOrderId(Long.parseLong(orderIdBySerialnNumber.get("id").toString()));
        payInfo.setPayPrice(price);
        payInfo.setPayTime(new Date());
        payInfo.setPayType("余额支付");
        payInfoService.insert(payInfo);
        BalanceDetails balanceDetails = new BalanceDetails();
        balanceDetails.setCreateTime(new Date());
        balanceDetails.setReason("支付订单");
        balanceDetails.setUid(user.getId());
        balanceDetails.setMoney(price);
        balanceDetailsService.insert(balanceDetails);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setMsg("购买成功");
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
}
